package com.atstudent.gmall.product.service.impl;

import com.atstudent.gmall.product.entity.BaseAttrValue;
import com.atstudent.gmall.product.mapper.BaseAttrValueMapper;
import com.atstudent.gmall.product.service.BaseAttrValueService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atstudent.gmall.product.entity.BaseAttrInfo;
import com.atstudent.gmall.product.service.BaseAttrInfoService;
import com.atstudent.gmall.product.mapper.BaseAttrInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
* @author xueyoupeng
* @description 针对表【base_attr_info(属性表)】的数据库操作Service实现
* @createDate 2023-09-05 14:39:24
*/
@Service
public class BaseAttrInfoServiceImpl extends ServiceImpl<BaseAttrInfoMapper, BaseAttrInfo>
    implements BaseAttrInfoService{

    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;

    @Autowired
    private BaseAttrValueService baseAttrValueService;

    @Override
    public List<BaseAttrInfo> findBaseAttrInfo(Long c1Id, Long c2Id, Long c3Id) {

        return baseAttrInfoMapper.findBaseAttrInfo(c1Id,c2Id,c3Id);
    }

    @Override
    @Transactional //涉及到多表操作 ， 要开启事务
    public void saveBaseAttrInfo(BaseAttrInfo baseAttrInfo) {

        //用id来判断是新增还是更新
        Long attrInfoId = baseAttrInfo.getId();
        if (attrInfoId == null){
            //先保存平台属性的数据
            this.save(baseAttrInfo);

            //再保存平台属性值的数据
            //缺少attr_id这个字段 先补全
            List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
            //遍历
            List<BaseAttrValue> baseAttrValues = attrValueList.stream().map(baseAttrValue -> {
                baseAttrValue.setAttrId(baseAttrInfo.getId());
                return baseAttrValue;
            }).collect(Collectors.toList());

            //保存数据
            baseAttrValueService.saveBatch(baseAttrValues);
        }else {

            //先更新属性的数据
            this.updateById(baseAttrInfo);

            //更新属性值的数据
            //先删除原来的属性值 根据属性的id 也就是属性值的attr_id
            QueryWrapper<BaseAttrValue> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("attr_id",attrInfoId);
            baseAttrValueService.remove(queryWrapper);

            //保存平台属性值的数据
            List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
            //遍历
            List<BaseAttrValue> baseAttrValues = attrValueList.stream().map(baseAttrValue -> {
                baseAttrValue.setId(null);
                baseAttrValue.setAttrId(baseAttrInfo.getId());
                return baseAttrValue;
            }).collect(Collectors.toList());
            //修改平台属性值
            baseAttrValueService.saveBatch(baseAttrValues);

        }
    }
}




